/**
 * SceneGame_Player
 * 	@brief  Player controller
 * 	@author Bruno Miguel de Oliveira Tamer <bmotamer@gmail.com>
 */

using UnityEngine;

public class SceneGame_Player : MonoBehaviour
{
	
	public AudioClip HitSound;
	
	public Vector2 Velocity;
	public float   BoostVelocity;
	public Rect    Bounds;
	public float   BaseVelocity;
	public float   Displacement;
	public Vector2 Offset;
	
	public void Start()
	{
		Displacement = transform.position.z;
	}
	
	public void Update()
	{
		if (SceneGame.Instance.Step > 1)
			return;
		
		float smoothDeltaTime = Mathf.Clamp(Time.smoothDeltaTime, 0.01666667f, float.MaxValue);
		
		Vector2 adjustment = new Vector2(
			Input.GetAxis("Horizontal") * Velocity.x,
			Input.GetAxis("Vertical") * Velocity.y
		) * smoothDeltaTime;
		
		//if (adjustment.x != 0.0f)
		Offset.x = Mathf.Clamp(
			Offset.x + adjustment.x,
			Bounds.xMin,
			Bounds.xMax
		);
		
		//if (adjustment.y != 0.0f)
		Offset.y = Mathf.Clamp(
			Offset.y + adjustment.y,
			Bounds.yMin,
			Bounds.yMax
		);
		
		Vector3 position = transform.position;
		
		position.x = Offset.x;
		position.z = Offset.y;
		
		float abs     = Mathf.Abs(Bounds.height) - Mathf.Abs(Bounds.y);
		Displacement += (BaseVelocity + (abs + Offset.y) / (2 * abs)  * BoostVelocity) * smoothDeltaTime;
		
		position.z += Displacement;
		
		transform.position = position;
	}
		
	public void OnCollisionEnter(Collision collision)
	{
		PushAway(collision);
	}
	
	public void OnCollisionStay(Collision collision)
	{
		PushAway(collision);
	}
	
	public void PushAway(Collision collision)
	{
		float highest = collision.contacts[0].point.x;
		float lowest  = collision.contacts[0].point.x;
		for (int i = 1; i < collision.contacts.Length; i++)
		{
			if (Mathf.Abs(highest) < Mathf.Abs(collision.contacts[i].point.x))
				highest = collision.contacts[i].point.x;
			if (Mathf.Abs(lowest) > Mathf.Abs(collision.contacts[i].point.x))
				lowest = collision.contacts[i].point.x;
		}
		
		if (lowest > transform.position.x)
			Offset.x = lowest - (lowest - transform.position.x);
		else
			Offset.x = lowest + (transform.position.x - lowest);
		
		rigidbody.velocity = Vector3.zero;
	}
	
	public void OnTriggerEnter(Collider collider)
	{
		if (!HitSound || (collider == null) || (collider.name == "Wall"))
			return;
		audio.PlayOneShot(HitSound);
	}
	
}